package br.org.bertol.mestrado;

import java.io.FileOutputStream;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import br.org.bertol.mestrado.engine.AbstractSearchEngine;
import br.org.bertol.mestrado.util.Configurator;

/**
 * @author contaqualquer
 * @param <E>
 *            Tipo de engine usado
 */
public abstract class AbstractStarter<E extends AbstractSearchEngine<?>> {

    /***/
    protected transient ArrayList<E> engineList;

    /***/
    protected transient Configurator configurator;

    /**
     * @param configurador
     *            Objeto que carrega as configurações
     */
    protected AbstractStarter(final Configurator configurador) {
        this.configurator = configurador;

        engineList = new ArrayList<E>();
    }

    /**
     * @throws InterruptedException
     *             Erro ao sincronizar thread
     */
    public abstract void startEngine() throws InterruptedException;

    /**
     * Pega as planilhas com os resultados detalhados.
     */
    public final void getResultSheet() {

        final Workbook workbook = new HSSFWorkbook();

        for (E e : engineList) {
            e.getResultSheet(workbook);
        }

        try {
            final FileOutputStream out = new FileOutputStream(configurator
                    .getSourcePath()
                    + "/" + configurator.getOutPutFile() + "/"
                    + getClass().getCanonicalName() + ".xls");
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            Logger.getLogger(getClass()).error("Erro ao salvar arquivo.", e);
        }

    }

}
